
// import { userStore } from '@/store/modules/user'
// import { getGuestToken } from '@/utils/storage'
import { message } from 'ant-design-vue'
import Markdown from 'markdown-it'

const mdOptions = {
  linkify: false,
  typographer: true,
  breaks: true,
  html: true
}

let mdHandle = new Markdown(mdOptions)
// 自定义渲染规则 a标签添加_blank属性
mdHandle.renderer.rules.link_open = function (tokens: any, idx: any, options: any, env: any, self: any) {
  const aIndex = tokens[idx].attrIndex('target')

  if (aIndex < 0) {
    tokens[idx].attrPush(['target', '_blank']) // 添加新属性
  } else {
    // 如果已存在，确保它的值是'_blank'
    const aValue = tokens[idx].attrs[aIndex]
    if (aValue[1] !== '_blank') {
      tokens[idx].attrs[aIndex][1] = '_blank'
    }
  }

  // 使用默认的处理方式
  return self.renderToken(tokens, idx, options)
}

export const md = mdHandle

let controller: any = null
let articleController: any = null

export async function qaChat(messageObj: any, queryType?: string) {
  // if (queryType === 'articleDetail') {
  //   articleController = new AbortController()
  // } else {
  //   controller = new AbortController()
  // }

  controller = new AbortController()
  // eslint-disable-next-line no-useless-catch
  const content = {
    ...messageObj,
    direction: 'Q'
  }

  // eslint-disable-next-line no-useless-catch
  try {
    // const userModule = userStore()
    // let tokenValue = userModule.token
    // const url = '/api/eims/BPai/V2/chat'
    // const url = '/api/node/stream'
    // const url = '/serve/api_BPai_QA_Stream'
    const url = '/api/api_QA_Stream'
    const result = await fetch(url, {
      method: 'post',
      signal: controller.signal,
      // TODO 优化
      // 开启后到达设定时间会中断流式输出
      headers: {
        'Content-Type': 'application/json',
        'Client-Type': 'browser',
        // Authorization: tokenValue || getGuestToken() || '' // `Bearer xxxxxxxxx`,
        // Authorization: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblVzZXJJZCI6IjE4NTQzNDI3NTAzMzgxNjY3ODQiLCJjbGllbnRUeXBlIjoiYnJvd3NlciIsImFwcElkIjoiQmlhb1B1WXVuIiwiZXhwIjoxNzM1MTE5MjYyfQ.FBEvY7zbSpAWu4R9hH16uQ3eISTDcdEIICzOfd7NHYo',
      },
      body: JSON.stringify(content)
    })

    let responseType = result.headers.get('Content-Type')
    if (responseType && responseType.includes('application/json')) {
      let resultJson = await result.json()
      console.log('resultJson--', resultJson);

      if (resultJson.code == '401') {
        console.log('登录失效');
      } else {
        message.error({
          content: resultJson.message,
          duration: 3
        })
      }
      throw resultJson
    }

    return result
  } catch (error) {
    throw error
  }
}

export const controllerAbort = () => {
  if (controller) {
    console.log('controller--',controller);
    
    controller.abort()
  }
}

export const articleControllerAbort = () => {
  if (articleController) {
    articleController.abort()
  }
}
